﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Light.Utility.Security
{
    public class Base64StringCryptor
    {

        public static int SaltLength = 4;

        public static string Encrypt(string plainStr)
        {
            Random rand = new Random();
            string salt = rand.Next((int)Math.Pow(10, SaltLength - 1), (int)Math.Pow(10, SaltLength) - 1).ToString();

            return Encrypt(plainStr, salt);
        }

        public static string Encrypt(string plainStr, string salt)
        {
            return Convert.ToBase64String(Encoding.Default.GetBytes(plainStr + salt));
        }

        public static string Decrypt(string cipherStr)
        {
            string plainStr = Encoding.Default.GetString(Convert.FromBase64String(cipherStr));
            if (plainStr.Length > SaltLength)
            {
                return plainStr.Substring(0, plainStr.Length - SaltLength);
            }
            return plainStr;
        }

        public static string Decrypt(string cipherStr, string salt)
        {
            string plainStr = Encoding.Default.GetString(Convert.FromBase64String(cipherStr));
            if (plainStr.Length > salt.Length)
            {
                return plainStr.Substring(0, plainStr.Length - salt.Length);
            }
            return plainStr;
        }

    }
}
